<template>
  <div class="dept-manage">
    <!-- 顶部标题 + 操作区 -->
    <div class="header">
      <h2 class="page-title">科室管理系统</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd" class="add-btn" :icon="Plus">
          新增科室
        </el-button>
        <!-- 搜索区域 -->
        <div class="search-group">
          <el-input 
            v-model="searchKey" 
            placeholder="搜索科室名称" 
            clearable 
            class="search-input"
            @keyup.enter="handleSearch"
          />
          <el-button type="primary" @click="handleSearch" class="search-btn" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" class="reset-btn" :icon="Refresh">
            重置
          </el-button>
        </div>
      </div>
    </div>

    <!-- 科室列表表格 -->
    <el-table 
      :data="tableData" 
      border 
      style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange"
      class="dept-table"
      stripe
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="department_id" label="ID" width="80"></el-table-column>
      <el-table-column prop="department_name" label="科室名称" min-width="120"></el-table-column>
      <el-table-column prop="level" label="层级" width="100">
        <template #default="scope">
          <el-tag 
            :type="scope.row.level === 1 ? 'primary' : 'success'" 
            effect="light"
          >
            {{ scope.row.level === 1 ? '一级科室' : '二级科室' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="parent_id" label="上级科室" width="120">
        <template #default="scope">
          {{ scope.row.parent_id === 0 ? '无上级' : getParentName(scope.row.parent_id) }}
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.create_time) }}
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button 
            link 
            :icon="Edit" 
            size="small"
            @click="handleEdit(scope.row)"
            class="action-btn"
            title="编辑"
          />
          <el-button 
            link 
            :icon="Delete" 
            size="small"
            @click="handleDelete(scope.row)"
            class="action-btn danger"
            title="删除"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 批量删除按钮 -->
    <div class="batch-actions">
      <el-button 
        type="danger" 
        :icon="Delete" 
        @click="handleBatchDelete"
        :disabled="selectedRows.length === 0"
        class="batch-delete-btn"
      >
        批量删除
      </el-button>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑科室' : '新增科室'" 
      width="500px" 
      class="custom-dialog"
      :before-close="handleDialogClose"
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="deptFormRef" 
        label-width="100px"
      >
        <el-form-item label="科室名称" prop="department_name">
          <el-input v-model="form.department_name" placeholder="请输入科室名称"></el-input>
        </el-form-item>
        <el-form-item label="层级" prop="level">
          <el-select v-model="form.level" placeholder="请选择层级" style="width: 100%">
            <el-option label="一级科室" value="1"></el-option>
            <el-option label="二级科室" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级科室" prop="parent_id">
          <el-select 
            v-model="form.parent_id" 
            placeholder="请选择上级科室" 
            style="width: 100%"
            :disabled="form.level === '1'"
          >
            <el-option label="无上级" value="0"></el-option>
            <el-option 
              v-for="item in parentOptions" 
              :key="item.department_id" 
              :label="item.department_name" 
              :value="item.department_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="create_time">
          <el-input 
            v-model="form.create_time" 
            placeholder="创建时间" 
            disabled 
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确认保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElButton, ElInput, ElDialog, ElForm, ElFormItem, ElSelect, ElOption, ElTag } from 'element-plus';
import { format } from 'date-fns';
import axios from 'axios';

// 正确定义API服务，确保全局唯一实例
const apiService = {
  getDepartments: () => axios.get('http://localhost:8080/hospital4_war/department/findAll'),
  addDepartment: (data) => axios.post('http://localhost:8080/hospital4_war/department/addDepartment', data, {
    headers: {'Content-Type': 'application/json'},
    transformRequest: [data => JSON.stringify(data)]
  }),
  updateDepartment: (data) => axios.post('http://localhost:8080/hospital4_war/department/updateDepartment', data),
  deleteDepartment: (id) => axios.delete(`http://localhost:8080/hospital4_war/department/deleteDepartment/${id}`)
};

// 验证上级科室选择
const validateParentId = (rule, value, callback) => {
  if (form.level === '1' && value !== '0') {
    callback(new Error('一级科室不能有上级科室'));
  } else if (form.level === '2' && value === '0') {
    callback(new Error('二级科室必须选择上级科室'));
  } else {
    callback();
  }
};

// 处理表格选择变化
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 日期格式化工具函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  return format(new Date(dateString), 'yyyy-MM-dd HH:mm:ss');
};

// 响应式数据
const tableData = ref([]);
const searchKey = ref('');
const dialogVisible = ref(false);
const isEdit = ref(false);
const form = reactive({
  department_id: '',
  department_name: '',
  level: '',
  parent_id: '0',
  create_time: ''
});
const rules = reactive({
  department_name: [
    { required: true, message: '请输入科室名称', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择层级', trigger: 'change' }
  ],
  parent_id: [
    { validator: validateParentId, trigger: 'change' }
  ]
});
const deptFormRef = ref(null);
const selectedRows = ref([]);
const parentOptions = ref([]);

// 错误处理函数
const handleApiError = (error, customErrorMsg = '操作失败') => {
  console.error('API错误:', error);
  let errorMsg = customErrorMsg;
  if (error.name === 'AbortError') {
    errorMsg = '请求超时，请检查服务器连接';
  } else if (error.response) {
    errorMsg = `服务器错误: ${error.response.data?.message || '内部服务器错误'}`;
  } else {
    errorMsg += `: ${error.message}`;
  }
  ElMessage.error(errorMsg);
};

// 获取所有科室数据
const fetchDepartments = async () => {
  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时
    console.log('请求科室数据:', { url: '/department/findAll', method: 'GET', timestamp: new Date().toISOString() });
    const response = await apiService.getDepartments({ signal: controller.signal });
    console.log('接口返回数据:', response.data);
    clearTimeout(timeoutId);
    tableData.value = response.data || [];
    updateParentOptions();
    localStorage.setItem('deptCache', JSON.stringify(tableData.value));
  } catch (error) {
    handleApiError(error, '获取科室数据失败');
    ElMessageBox.confirm('是否重试加载数据?', '加载失败', {
      confirmButtonText: '重试',
      cancelButtonText: '取消',
      type: 'question'
    }).then(() => {
      fetchDepartments();
    }).catch(() => {
      // 尝试从localStorage读取缓存数据
      const cachedData = localStorage.getItem('deptCache');
      if (cachedData) {
        tableData.value = JSON.parse(cachedData);
        updateParentOptions();
        ElMessage.success('已加载缓存数据');
      } else {
        tableData.value = [];
        ElMessage.info('暂无缓存数据');
      }
    });
  }
};

// 搜索科室
const handleSearch = async () => {
  try {
    const response = await apiService.getDepartments();
    // 添加searchKey空值检查
    const lowerKey = searchKey.value ? searchKey.value.toLowerCase() : '';
    tableData.value = response.data.filter(item => 
      item.department_name && item.department_name.toLowerCase().includes(lowerKey)
    );
  } catch (error) {
    handleApiError(error, '搜索失败');
  }
};

// 重置搜索
const handleReset = () => {
  searchKey.value = '';
  fetchDepartments();
};

// 新增科室
const handleAdd = () => {
  // 重置表单数据
  form.department_id = '';
  form.department_name = '';
  form.level = '1';
  form.parent_id = '0';
  form.create_time = format(new Date(), 'yyyy-MM-dd HH:mm:ss');
  isEdit.value = false;
  dialogVisible.value = true;
};

// 编辑科室
const handleEdit = (row) => {
  form.department_id = row.department_id;
  form.department_name = row.department_name;
  form.level = row.level.toString();
  form.parent_id = row.parent_id.toString();
  form.create_time = formatDate(row.create_time);
  isEdit.value = true;
  dialogVisible.value = true;
};

// 保存科室数据
const handleSave = async () => {
  try {
    // 打印完整表单数据用于调试
    console.log('表单完整数据:', form);
    
    // 科室名称必填验证
    if (!form.department_name || form.department_name.trim() === '') {
      ElMessage.error('科室名称不能为空');
      return;
    }
    
    // 层级与父科室验证
    if (form.level === '2' && (form.parent_id === '0' || !form.parent_id)) {
      ElMessage.error('二级科室必须选择父科室');
      return;
    }
    
    await deptFormRef.value.validate();
    
    let response;
    if (isEdit.value) {
      // 更新科室
      const submitData = {
        department_id: form.department_id,
        department_name: form.department_name.trim(),
        level: Number(form.level),
        ...(form.level === '2' && { parent_id: Number(form.parent_id) })
      };
      
      console.log('编辑提交数据:', submitData);
      response = await apiService.updateDepartment(submitData);
    } else {
      // 新增科室
      const submitData = {
        department_name: form.department_name.trim(),
        level: Number(form.level),
        ...(form.level === '2' && { parent_id: Number(form.parent_id) })
      };
      
      console.log('提交科室数据:', submitData);
      response = await apiService.addDepartment(submitData);
    }
    
    if (response && (response.status === 200 || response.status === 201)) {
      ElMessage.success(isEdit.value ? '科室更新成功' : '科室创建成功');
      fetchDepartments();
      dialogVisible.value = false;
    } else {
      throw new Error(`API错误: 状态码=${response?.status || '未知'}, 响应内容=${JSON.stringify(response?.data)}`);
    }
  } catch (error) {
    console.error('保存科室详细错误:', error);
    ElMessage.error(`${isEdit.value ? '更新' : '新增'}科室失败: ${error.message}`);
  }
};

// 删除科室
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '此操作将永久删除该科室, 是否继续?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await apiService.deleteDepartment(row.department_id);
    ElMessage.success('科室删除成功');
    fetchDepartments();
  } catch (error) {
    if (error.name !== 'Cancel') {
      handleApiError(error, '删除科室失败');
    } else {
      ElMessage.info('已取消删除');
    }
  }
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的科室');
    return;
  }
  
  ElMessageBox.confirm(
    '确定删除选中的' + selectedRows.value.length + '个科室？此操作不可恢复！',
    '提示',
    { type: 'warning' }
  ).then(async () => {
    const ids = selectedRows.value.map(item => item.department_id);
    try {
      for (const id of ids) {
        await apiService.deleteDepartment(id);
      }
      
      ElMessage.success('批量删除成功！');
      fetchDepartments();
      selectedRows.value = [];
    } catch (error) {
      handleApiError(error, '批量删除失败');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 关闭弹窗前验证
const handleDialogClose = (done) => {
  if (deptFormRef.value) {
    deptFormRef.value.clearValidate();
  }
  done();
};

// 更新上级科室选项
const updateParentOptions = () => {
  parentOptions.value = tableData.value.filter(item => item.level === 1);
};

// 根据ID获取上级科室名称
const getParentName = (parentId) => {
  const parent = tableData.value.find(item => item.department_id === parentId);
  return parent ? parent.department_name : '未知';
};

// 监听层级变化，更新上级科室选择框状态
watch(() => form.level, (newVal) => {
  if (newVal === '1') {
    form.parent_id = '0';
  }
});

// 初始化加载数据
onMounted(() => {
  fetchDepartments();
});
</script>

<style scoped>
/* 基础布局 */
.dept-manage {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 头部样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

/* 头部操作区 */
.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.add-btn {
  background-color: #409EFF;
  color: #fff;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s ease;
}

.add-btn:hover {
  background-color: #66b1ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 搜索组样式 */
.search-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-input {
  width: 280px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  padding: 8px 12px;
  transition: border-color 0.3s ease;
}

.search-input:focus {
  border-color: #409EFF;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.search-btn, .reset-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  transition: all 0.3s ease;
}

.search-btn {
  background-color: #409EFF;
  color: #fff;
  border-radius: 4px;
}

.search-btn:hover {
  background-color: #66b1ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.reset-btn {
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.reset-btn:hover {
  color: #303133;
  border-color: #c0c4cc;
  background-color: #f5f7fa;
}

/* 表格样式 */
.dept-table {
  --el-table-header-text-color: #303133;
  --el-table-header-background-color: #f0f2f5;
  --el-table-row-hover-bg-color: #f8f9fa;
  --el-table-odd-row-bg-color: #ffffff;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.dept-table th {
  font-weight: 500;
}

/* 层级标签样式（一级、二级科室） */
.el-tag {
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.el-tag--primary {
  background-color: #ecf5ff;
  color: #409EFF;
}

.el-tag--success {
  background-color: #f0f9eb;
  color: #67C23A;
}

/* 操作按钮样式 */
.action-btn {
  padding: 0 8px;
  color: #409EFF;
  transition: all 0.3s ease;
}

.action-btn.danger {
  color: #f56c6c;
}

.action-btn:hover {
  transform: translateY(-2px);
  color: #3a8ee6;
}

.action-btn.danger:hover {
  color: #ff7a7a;
}

/* 批量删除按钮 */
.batch-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.batch-delete-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background-color: #f56c6c;
  color: #fff;
  border-radius: 4px;
  transition: all 0.3s ease;
  border: none;
}

.batch-delete-btn:hover {
  background-color: #e53935;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

/* 弹窗样式 */
.custom-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.custom-dialog .el-dialog__header {
  background-color: #f0f2f5;
  padding: 16px 24px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.custom-dialog .el-dialog__title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.custom-dialog .el-dialog__body {
  padding: 24px;
}

.custom-dialog .el-dialog__footer {
  text-align: right;
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    flex-wrap: wrap;
    justify-content: flex-start;
    gap: 10px;
  }
  
  .search-group {
    width: 100%;
  }
  
  .search-input {
    width: 100%;
  }
  
  .dept-manage {
    padding: 15px;
  }
  
  .dept-table {
    font-size: 12px;
  }
}
</style>